package com.bsb.biz.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.bsb.base.common.config.Global;
import com.bsb.base.common.config.Title;
import com.bsb.base.common.config.Title2;
import com.bsb.base.common.util.DateUtils;
import com.bsb.base.common.util.IdGen;
import com.bsb.base.common.util.Md5Util;
import com.bsb.base.common.util.StringUtils;
import com.bsb.base.model.BsbUser;
import com.bsb.base.model.BsbUserExample;
import com.bsb.base.model.BsbUserExample.Criteria;
import com.bsb.biz.service.BsbUserService;
import com.bsb.biz.service.ValidateCodeService;
import com.bsb.biz.shiro.UserUtils;

@Controller
@RequestMapping("/bsbCounselor")
public class BsbCounselorController{
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/bsbCounselor/list.do";
	
	@Resource
	private BsbUserService bsbUserService;
	@Resource
	private ValidateCodeService validateCodeService;
	
	@RequiresPermissions("bsbCounselor:view")
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(
			Model model,@RequestParam Map<String, Object> params,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		String name = (String) params.get("name");
		String phone = (String) params.get("phone");
		String start = (String) params.get("start");
		Date startDate = DateUtils.parseDate(start);
		String end = (String) params.get("end");
		Date endDate = DateUtils.parseDate(end);
		BsbUserExample bsbUserExample = new BsbUserExample();
		Criteria criteria = bsbUserExample.createCriteria();
		criteria.andRoleEqualTo("3");//咨询师
		criteria.andDelFlagEqualTo(Global.SHOW);
		criteria.andFirmIdEqualTo(UserUtils.currentUser().getFirmId()==null?0:UserUtils.currentUser().getFirmId().intValue());
		if(StringUtils.isNotEmpty(phone)){
			criteria.andPhoneLike("%"+phone+"%");
		}
		if(StringUtils.isNotEmpty(name)){
			criteria.andNameLike("%"+name+"%");
		}
		if(null != startDate){
			criteria.andRegistTimeGreaterThanOrEqualTo(startDate);
		}
		if(null != endDate){
			endDate = DateUtils.addDays(endDate, 1);
			criteria.andRegistTimeLessThanOrEqualTo(endDate);
		}
		int totalCount = bsbUserService.countBsbUser(bsbUserExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		bsbUserExample.setPageIndex((pageNum - 1) * pageSize);
		bsbUserExample.setPageSize(pageSize);
		List<BsbUser> bsbUsers = bsbUserService.getPageBsbUser(bsbUserExample);
		for (BsbUser bsbUser : bsbUsers) {
			String duty = bsbUser.getDuty();
			bsbUser.setDuty(Title.getNames(duty));
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("name", name);
		model.addAttribute("phone", phone);
		model.addAttribute("start", start);
		model.addAttribute("end", end);
		model.addAttribute("bsbUsers", bsbUsers);
		return "/BsbCounselor/list";
	}
	
	private void setCommonData(Model model) {
		List<Title2> titles = Title2.getList();
		model.addAttribute("titles", titles);
	}
	
	@RequiresPermissions("bsbCounselor:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String toAdd(Model model,HttpServletRequest request,RedirectAttributes redirectAttributes) {
		String queryString = request.getQueryString();
		setCommonData(model);
		Long firmId = UserUtils.currentUser().getFirmId();
		if(null == firmId){
			redirectAttributes.addFlashAttribute("msg", "事务所信息有误，无法添加咨询师");
			return redirect+ "?" +queryString;
		}
		return "/BsbCounselor/add";
	}

	@RequiresPermissions("bsbCounselor:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@ResponseBody
	public Object add(Model model, @ModelAttribute("bsbUser") BsbUser bsbUser,
			@RequestParam(value="code",required = true) String code) {
		Map<String,Object> map = new HashMap<String,Object>();
		if(StringUtils.isEmpty(code)){
			map.put("status", false);
			map.put("msg", "验证码不能为空");
			return map;
		}
		String phone = bsbUser.getPhone();
		if(!StringUtils.isMobile(phone)){
			map.put("status", false);
			map.put("msg", "手机号格式不正确");
			return map;
		}
		String pwd = bsbUser.getPwd();
		if(StringUtils.isEmpty(pwd)){
			map.put("status", false);
			map.put("msg", "初始密码不能为空");
			return map;
		}
		if(!validateCodeService.checkSmsCode(code)){
			map.put("status", false);
			map.put("msg", "验证码错误");
			return map;
		}
		BsbUser userByPhone = bsbUserService.getUserByPhone(phone);
		if(null != userByPhone){
			map.put("status", false);
			map.put("msg", "该手机号码已存在");
			return map;
		}
		try {
			bsbUser.setUuid(IdGen.uuid());
			bsbUser.setRegistTime(new Date());
			bsbUser.setPwd(Md5Util.Md5(pwd));
			bsbUser.setRole("3");//专家
			bsbUser.setFirmId(UserUtils.currentUser().getFirmId().intValue());//挂在解税宝下
			bsbUserService.addBsbUser(bsbUser);
			map.put("status", true);
			map.put("msg", "添加成功");
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", false);
			map.put("msg", "系统繁忙，请联系管理员");
			return map;
		}
		
	}
	
	@RequiresPermissions("bsbCounselor:delete")
	@RequestMapping(value = "/{uuid}/delete", method = RequestMethod.GET)
	public String del(Model model,
			@PathVariable("uuid") String uuid) {
		BsbUser bsbUser = new BsbUser();
		bsbUser.setUuid(uuid);
		bsbUser.setDelFlag(Global.HIDE);
		bsbUserService.updateBsbUser(bsbUser );
		return redirect;
	}
	
	@RequiresPermissions("bsbCounselor:update")
	@RequestMapping(value = "/{uuid}/update", method = RequestMethod.GET)
	public String toEdit(Model model,HttpServletRequest request,
			@PathVariable("uuid") String uuid) {
		BsbUser bsbUser = bsbUserService.getBsbUserByUuid(uuid);
		setCommonData(model);
		model.addAttribute("bsbUser", bsbUser);
		String queryString = request.getQueryString();
		model.addAttribute("queryString", queryString);
		return "/BsbCounselor/edit";
	}

	@RequiresPermissions("bsbCounselor:update")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String edit(Model model,
			@RequestParam(value = "queryString", required = false) String queryString,
			@ModelAttribute("bsbUser") BsbUser bsbUser) {
		bsbUserService.updateBsbUser(bsbUser);
		return redirect+ "?" +queryString;
	}
	
	@RequiresPermissions("bsbCounselor:view")
	@RequestMapping(value = "/{uuid}/view", method = RequestMethod.GET)
	public String view(Model model,
			@PathVariable("uuid") String uuid) {
		BsbUser bsbUser = bsbUserService.getBsbUserByUuid(uuid);
		String duty = bsbUser.getDuty();
		bsbUser.setDuty(Title.getNames(duty));
		model.addAttribute("bsbUser", bsbUser);
		return "/BsbCounselor/view";
	}
	
	
}
